package com.swang.framework.core.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: HttpUtil
 * @Description: TODO
 * @author: swang@swang.com
 * @date: 2017年3月16日 下午9:45:51
 */
public class HttpUtil {
    private static Logger     log = Logger.getLogger(HttpUtil.class);
    private static HttpClient httpClient;

    /**
     * 获取webcontext完整路径
     * 
     * @param request
     * @return
     */
    public static String getBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    /**
     * 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     * 
     * @param URL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> urlRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit = null;

        String strUrlParam = truncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        // 每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    // 只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     * 
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim().toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }

        return strAllParam;
    }

    /**
     * 发送Post请求, JSON串参数
     * 
     * @throws ClientProtocolException
     * @throws IOException
     */
    //------------------------------------------------------------------
    public static String postForJson(String url, String json) throws ClientProtocolException, IOException {
        log.debug("====>http请求-->请求地址:" + url);
        String resultJson = "";
        httpClient = HttpClientBuilder.create().build();

        //请求头
        StringEntity entity = new StringEntity(json);
        entity.setContentType("application/json");
        entity.setContentEncoding("utf-8");

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        httpPost.addHeader("Accept", "application/json");

        //发起请求
        HttpResponse response = httpClient.execute(httpPost);
        int httpStatus = response.getStatusLine().getStatusCode();
        if (httpStatus != 200) {
            return resultJson;
        }

        log.debug("====>http请求-->返回状态:" + response.getStatusLine().getReasonPhrase());

        //结果转换成json
        HttpEntity httpEntity = response.getEntity();
        httpEntity.getContent();
        resultJson = EntityUtils.toString(response.getEntity());

        log.debug("====>http请求-->返回字符串:" + resultJson);
        return resultJson;
    }

    public static String getForJson(String url) throws IOException {
        log.debug("====>http请求-->请求地址:" + url);
        String resultJson = "";
        httpClient = HttpClientBuilder.create().build();
        //请求头
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Accept", "application/json");
        //发起请求
        HttpResponse response = httpClient.execute(httpGet);
        int httpStatus = response.getStatusLine().getStatusCode();
        if (httpStatus != 200)
            return resultJson;
        log.debug("====>http请求-->返回状态:" + response.getStatusLine().getReasonPhrase());
        //结果转换成json
        HttpEntity httpEntity = response.getEntity();
        httpEntity.getContent();
        resultJson = EntityUtils.toString(response.getEntity());
        log.debug("====>http请求-->返回字符串:" + resultJson);
        return resultJson;
    }

    /**
     * 发送Http Post请求
     * 
     * @param url : URL路径
     * @param map : 参数
     * @return
     */
    public static String sendHttpPostRequest(String url, Map<String, Object> map) {

        return null;
    }

}
